package com.naughty.shopapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.naughty.shopapi.mapper.CartMapper;
import com.naughty.shopapi.mapper.GoodsMapper;
import com.naughty.shopapi.mapper.UsersMapper;
import com.naughty.shopapi.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.naughty.shopapi.utils.JWTUtil.isExpiration;

@Api(tags = "购物车操作")
@RestController
@RequestMapping("api")
public class CartsController {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 添加购物车
     *
     * @param goods_id 商品ID
     * @param num      商品数量
     * @return
     */
    @ApiOperation("添加商品到购物车")
    @PostMapping("/carts")
    public ResponseEntity<Object> insertCarts(
            @RequestParam String goods_id,
            @RequestParam(defaultValue = "1") String num
    ) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                final RegisterErrors registerErrors = new RegisterErrors();
                final HashMap<String, Object> errormsg = new HashMap<>();
                final ArrayList<Object> goodsIdMsg = new ArrayList<>();
                Boolean goodsIdBoo = false;
                int numAbs = 1;
                if (Integer.parseInt(String.valueOf(num)) <= 1) {
                    numAbs = 1;
                } else {
                    numAbs = Math.abs(Integer.parseInt(String.valueOf(num)));
                }
                int GoodsId = 0;
                if (goods_id == "") {//name 条件
                    goodsIdMsg.add("商品ID 不能为空");
                    errormsg.put("goods_id", goodsIdMsg);
                } else {
                    GoodsId = Integer.parseInt(String.valueOf(goods_id));   //绝对值赋值
                    final HashMap<String, Object> isGoodsMap = new HashMap<>();
                    isGoodsMap.put("id", GoodsId);
                    final List<Goods> isGoods = goodsMapper.selectByMap(isGoodsMap);
                    if (isGoods.size() == 0) {
                        goodsIdMsg.add("商品 不存在");
                        errormsg.put("goods_id", goodsIdMsg);
                    } else {
                        //goods_id 格式正确
                        goodsIdBoo = true;
                    }
                }

                if (goodsIdBoo) {
                    final QueryWrapper<Cart> wrapperCart = new QueryWrapper<>();
                    wrapperCart.eq("user_id", isToken.get(0).getId());
                    wrapperCart.eq("goods_id", GoodsId);
                    List<Cart> objCart = cartMapper.selectList(wrapperCart);
                    if (objCart.size() == 0) {//该用户没有添加过此商品到购物车
                        final Cart cart = new Cart();
                        cart.setUser_id(isToken.get(0).getId());
                        cart.setGoods_id(GoodsId);
                        cart.setNum(numAbs);
                        cartMapper.insert(cart);
                        return new ResponseEntity<>(null, HttpStatus.CREATED);
                    } else {//该用户添加过此商品到购物车
                        final Integer numGood = objCart.get(0).getNum();
                        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", objCart.get(0).getId()).set("num", (numGood + numAbs));
                        cartMapper.update(null, updateWrapper);
                        return new ResponseEntity<>(null, HttpStatus.CREATED);
                    }
                } else {
                    registerErrors.setMessage("The given data was invalid.");
                    registerErrors.setErrors(errormsg);
                    registerErrors.setStatus_code(422);
                    return new ResponseEntity<>(registerErrors, HttpStatus.UNPROCESSABLE_ENTITY);
                }

            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }

    /**
     * 购物车列表
     *
     * @param include 包含内容(一般传值固定为：goods)
     * @return
     */
    @ApiOperation("获取用户购物车列表")
    @GetMapping("/carts")
    public ResponseEntity<Object> getCartsList(@RequestParam String include) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                if (include.equals("goods")) {
                    List<CartVO> CartOUT = new ArrayList<>();
                    final CartListVO cartListVO = new CartListVO();
                    final QueryWrapper<Cart> wrapperCart = new QueryWrapper<>();
                    wrapperCart.eq("user_id", isToken.get(0).getId());
                    List<Cart> objCart = cartMapper.selectList(wrapperCart);
                    for (int i = 0; i < objCart.size(); i++) {
                        final CartVO cartVO = new CartVO();
                        final Goods goods = new Goods();
                        cartVO.setId(objCart.get(i).getId());
                        cartVO.setUser_id(objCart.get(i).getUser_id());
                        cartVO.setGoods_id(objCart.get(i).getGoods_id());
                        cartVO.setNum(objCart.get(i).getNum());
                        cartVO.setIs_checked(objCart.get(i).getIs_checked());

                        final QueryWrapper<Goods> wrapperGood = new QueryWrapper<>();
                        wrapperGood.eq("id", objCart.get(i).getGoods_id());
                        List<Goods> objGood = goodsMapper.selectList(wrapperGood);

                        goods.setId(objGood.get(0).getId());
                        goods.setUser_id(objGood.get(0).getUser_id());
                        goods.setCategory_id(objGood.get(0).getCategory_id());
                        goods.setTitle(objGood.get(0).getTitle());
                        goods.setDescription(objGood.get(0).getDescription());
                        goods.setPrice(objGood.get(0).getPrice());
                        goods.setStock(objGood.get(0).getStock());
                        goods.setSales(objGood.get(0).getSales());
                        goods.setCover(objGood.get(0).getCover());
                        goods.setPics(objGood.get(0).getPics());
                        goods.setIs_on(objGood.get(0).getIs_on());
                        goods.setIs_recommend(objGood.get(0).getIs_recommend());
                        goods.setDetails(objGood.get(0).getDetails());
                        goods.setCreated_at(objGood.get(0).getCreated_at());
                        goods.setUpdated_at(objGood.get(0).getUpdated_at());
                        goods.setCollects_count(objGood.get(0).getCollects_count());
                        goods.setCover_url(objGood.get(0).getCover_url());
                        goods.setPics_url(objGood.get(0).getPics_url());
                        goods.setIs_collect(objGood.get(0).getIs_collect());

                        cartVO.setGoods(goods);
                        cartVO.setCreated_at(objCart.get(i).getCreated_at());
                        cartVO.setUpdated_at(objCart.get(i).getUpdated_at());
                        CartOUT.add(cartVO);
                    }
                    cartListVO.setData(CartOUT);
                    return new ResponseEntity<>(cartListVO, HttpStatus.OK);
                } else {
                    return new ResponseEntity<>(null, HttpStatus.FORBIDDEN);
                }
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }

    /**
     * 购物车数量改变
     *
     * @param cart 购物车ID
     * @param num  商品数量 至少是1
     * @return
     */
    @ApiOperation("修改购物车数量")
    @PutMapping("/carts/{cart}")
    public ResponseEntity<Object> alterCarts(
            @PathVariable("cart") Integer cart,
            @RequestParam String num
    ) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                final RegisterErrors registerErrors = new RegisterErrors();
                final HashMap<String, Object> errormsg = new HashMap<>();
                final ArrayList<Object> numMsg = new ArrayList<>();
                final ArrayList<Object> cartMsg = new ArrayList<>();
                Boolean numBoo = false, cartBoo = false;
                int numAbs = 1;
                int cartAbs = 1;
                if (cart <= 1) {
                    cartAbs = 1;
                } else {
                    cartAbs = Math.abs(cart);
                }

                if (num.equals("")) {//name 条件
                    numMsg.add("数量 不能为空");
                    errormsg.put("num", numMsg);
                } else {
                    if (Integer.parseInt(String.valueOf(num)) <= 1) {
                        numAbs = 1;
                    } else {
                        numAbs = Math.abs(Integer.parseInt(String.valueOf(num)));
                    }
                    numBoo = true;
                }


                final QueryWrapper<Cart> wrapperCart = new QueryWrapper<>();
                wrapperCart.eq("user_id", isToken.get(0).getId());
                wrapperCart.eq("id", cartAbs);
                final List<Cart> isCarts = cartMapper.selectList(wrapperCart);
                if (isCarts.size() == 0) {//cart 条件
                    cartMsg.add("购物车ID 找不到");
                    errormsg.put("cart", cartMsg);
                } else {
                    cartBoo = true;
                }
                if (numBoo && cartBoo) {
                    final UpdateWrapper<Cart> CartUpdateWrapper = new UpdateWrapper<>();
                    CartUpdateWrapper.eq("user_id", isToken.get(0).getId())
                            .eq("id", cartAbs)
                            .set("num", numAbs);
                    cartMapper.update(null, CartUpdateWrapper);
                    return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
                } else {
                    registerErrors.setMessage("The given data was invalid.");
                    registerErrors.setErrors(errormsg);
                    registerErrors.setStatus_code(422);
                    return new ResponseEntity<>(registerErrors, HttpStatus.UNPROCESSABLE_ENTITY);
                }
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }

    /**
     * 移出购物车
     *
     * @param cart 购物车ID
     * @return
     */
    @ApiOperation("删除购物车")
    @DeleteMapping("/carts/{cart}")
    public ResponseEntity<Object> deleteCarts(@PathVariable("cart") Integer cart) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                final RegisterErrors registerErrors = new RegisterErrors();
                final HashMap<String, Object> errormsg = new HashMap<>();
                final ArrayList<Object> cartMsg = new ArrayList<>();
                int cartAbs = 1;
                if (cart <= 1) {
                    cartAbs = 1;
                } else {
                    cartAbs = Math.abs(cart);
                }

                Boolean cartBoo = false;
                final QueryWrapper<Cart> wrapperCart = new QueryWrapper<>();
                wrapperCart.eq("user_id", isToken.get(0).getId());
                wrapperCart.eq("id", cartAbs);
                final List<Cart> isCarts = cartMapper.selectList(wrapperCart);
                if (isCarts.size() == 0) {//cart 条件
                    cartMsg.add("购物车ID 找不到");
                    errormsg.put("cart", cartMsg);
                } else {
                    cartBoo = true;
                }

                if (cartBoo) {
                    final HashMap<String, Object> map = new HashMap<>();
                    map.put("id", cartAbs);
                    cartMapper.deleteByMap(map);
                    return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
                } else {
                    registerErrors.setMessage("The given data was invalid.");
                    registerErrors.setErrors(errormsg);
                    registerErrors.setStatus_code(422);
                    return new ResponseEntity<>(registerErrors, HttpStatus.UNPROCESSABLE_ENTITY);
                }
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }
    }

    /**
     * 购物车改变选中
     * 存在购物车id--->is_checked改为1，其他为0，全部不存在将为0
     *
     * @param cart_ids 要操作的购物车id数组, {0:2, 1:3} => [2, 3]，传入为数组：{"cart_ids":[]}
     * @return
     */
    @ApiOperation("购物车选中状态改变")
    @PatchMapping("/carts/checked")
    public ResponseEntity<Object> checkedCartsArray(@RequestBody Map cart_ids) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        final String Authorization = request.getHeader("authorization");
        String[] tokens = Authorization.split(" ");
        String token = tokens[1];
        final HashMap<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("remember_token", token);
        final List<Users> isToken = usersMapper.selectByMap(tokenMap);
        if (isToken.size() == 0) {
            final RegisterErrors registerErrors = new RegisterErrors();
            registerErrors.setMessage("The token has been blacklisted.");
            registerErrors.setErrors("Token已被列入黑名单");
            registerErrors.setStatus_code(401);
            return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
        } else {
            if (!isExpiration(token)) {//判断token有效期
                final List<Integer> cartIds = (List<Integer>) cart_ids.get("cart_ids");//[4, 3, 1]
                if (cartIds.size() == 0) {
                    //没有传入值，全否
                    final QueryWrapper<Cart> wrapperCart = new QueryWrapper<>();
                    wrapperCart.eq("user_id", isToken.get(0).getId());
                    final List<Cart> userCartsList = cartMapper.selectList(wrapperCart);//该用户所有的购物车列表
                    //所有购物车is_checked=0
                    for (int i = 0; i < userCartsList.size(); i++) {
                        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", userCartsList.get(i).getId()).set("is_checked", 0);
                        cartMapper.update(null, updateWrapper);
                    }
                    return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
                } else {
                    //存在值，根据值进行check
                    final QueryWrapper<Cart> wrapperCartCheck = new QueryWrapper<>();
                    wrapperCartCheck.eq("user_id", isToken.get(0).getId())
                            .in("id", cartIds);
                    final List<Cart> userCartsListCheck = cartMapper.selectList(wrapperCartCheck);//cart_id以外的该用户其他购物车列表
                    for (int i = 0; i < userCartsListCheck.size(); i++) {//is_checked==>0
                        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", userCartsListCheck.get(i).getId()).set("is_checked", 1);
                        cartMapper.update(null, updateWrapper);
                    }

                    final QueryWrapper<Cart> wrapperCartNotCheck = new QueryWrapper<>();
                    wrapperCartNotCheck.eq("user_id", isToken.get(0).getId())
                            .notIn("id", cartIds);
                    final List<Cart> userCartsListNotCheck = cartMapper.selectList(wrapperCartNotCheck);//cart_id以外的该用户其他购物车列表
                    for (int i = 0; i < userCartsListNotCheck.size(); i++) {//is_checked==>0
                        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", userCartsListNotCheck.get(i).getId()).set("is_checked", 0);
                        cartMapper.update(null, updateWrapper);
                    }
                    return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
                }
            } else {
                final RegisterErrors registerErrors = new RegisterErrors();
                registerErrors.setMessage("Token Signature could not be verified.");
                registerErrors.setErrors("Token已失效");
                registerErrors.setStatus_code(401);
                return new ResponseEntity<>(registerErrors, HttpStatus.UNAUTHORIZED);
            }
        }


    }

}
